<template>
  <el-table :data="cartData" style="width: 100%">
    <el-table-column label="图片" width="240" align="center">
      <template #default="{ row }">
        <img
          :src="row.book.coverImageUrl"
          alt=""
          style="width: 200px; height: 240px"
        />
      </template>
    </el-table-column>
    <el-table-column
      prop="book.title"
      label="书名"
      width="240"
      align="center"
    ></el-table-column>
    <el-table-column
      prop="book.price"
      label="单价"
      width="100"
      align="center"
    ></el-table-column>

    <el-table-column
      prop="book.quantity"
      label="数量"
      width="240"
      align="center"
    >
      <template #default="{row}">
        <el-input
          v-model.number="row.quantity"
          class="center-text smaller-input"
          type="number"
          @blur="updateCartItemQuantity(row)"
        ></el-input>
      </template>
    </el-table-column>
    <el-table-column label="总价">
      <template #default="{ row }">
        {{ row.book.price * row.quantity }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="{row}">
        <el-button type="danger" @click="deleteItem(row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
    <!-- 其他列... -->
  </el-table>
  <div class="order-footer">
    <div class="total-price">合计：{{ totalSumPrice }}</div>
    <el-button type="primary" @click="checkout">结算</el-button>
  </div>
</template>
<script>
import { ElMessage } from "element-plus";
import API from "../../api/API";
import { definedUser } from "@/store/store";
export default {
  name: "Cart",
  data() {
    return {
      cartData: [],
      editIndex: -1,
      userId: definedUser().userId,
      totalSumPrice: 0,
    };
  },
  mounted(){
    API.getCart(definedUser().userId)
      .then((response) => {
        this.cartData = response.data.data;
        this.totalSumPrice = this.cartData.reduce(
        (sum, item) => sum + item.book.price * item.quantity,0
      );
      })
      .catch((error) => {
        console.error("Error fetching announcements:", error);
      });
  },
  methods: {
    checkout() {
      this.$router.push("/home/OrderForm");
    },
    updateCartItemQuantity(item) {
      // 假设有一个API用于更新购物车项的数量
      let newItem = {
        quantity:0
      }
      newItem.quantity = item.quantity
      API.updateCartItem(this.userId, item.detailId, newItem)
        .then(() => {
          this.calculateTotalSumPrice(); // 更新总价
        })
        .catch((error) => {
          console.error("Error updating cart item quantity:", error);
        });
    },
    deleteItem(item){

        API.deleteCartItem(this.userId, item.detailId)
        .then((response)=>{
          if (response.data.status == "200") {
            ElMessage.success("操作成功");
            API.getCart(definedUser().userId)
            .then((response) => {
              this.cartData = response.data.data;
              this.totalSumPrice = this.cartData.reduce(
              (sum, item) => sum + item.book.price * item.quantity,0
            );
            })
            .catch((error) => {
              console.error("Error fetching announcements:", error);
            });
          } else {
            ElMessage.error("删除失败");
          }
          
        })
        .catch(()=>{ElMessage.success("内部错误")})
    },
    calculateTotalSumPrice() {
      this.totalSumPrice = this.cartData.reduce(
        (sum, item) => sum + item.book.price * item.quantity,0
      );
    },

    // 其他方法...
  },
};
</script>
<style>
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.center-text {
  text-align: center;
}

.smaller-input {
  width: 100px; /* 或者你想要的任何宽度 */
  height: 30px; /* 或者你想要的任何高度 */
}
</style>
